package com.synnex.mobile.servier.web.content.controller.admin;

import com.sun.jmx.snmp.SnmpUnknownModelLcdException;
import com.synnex.mobile.generic.core.exception.SystemException;
import com.synnex.mobile.generic.core.util.MultiValueMap;
import com.synnex.mobile.generic.core.util.ObjectUtil;
import com.synnex.mobile.generic.core.util.StringUtil;
import com.synnex.mobile.generic.log.dao.annotation.LogClass;
import com.synnex.mobile.generic.log.dao.annotation.LogMethod;
import com.synnex.mobile.generic.log.entity.LogEntry;
import com.synnex.mobile.generic.web.anotation.mapping.RequestMapping;
import com.synnex.mobile.generic.web.view.JspView;
import com.synnex.mobile.generic.web.view.ModelAndView;
import com.synnex.mobile.generic.web.view.RedirectView;
import com.synnex.mobile.generic.web.view.View;
import com.synnex.mobile.servier.core.content.bo.ContentBo;
import com.synnex.mobile.servier.web.content.controller.AbstractContentController;
import com.synnex.mobile.servier.web.content.form.ContentForm;
import com.synnex.mobile.servier.web.utils.DateUtil;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kerryf
 */
@RequestMapping(url = "/admin")
@LogClass(name = "admin content")
public class AdminContentController extends AbstractContentController {


    @RequestMapping(url = "/listContent.do")
    @LogMethod(name = "get Content by type")
    public ModelAndView listContent(HttpServletRequest request, HttpServletResponse response) {
        try {
            LogEntry log = this.getAdminSession(request).getCurrentLogEntry(request);
            List<ContentBo> contentBoList = contentService.getContentByType(request.getParameter("type"));
            Map<String, Object> model = new HashMap<String, Object>();
            model.put("results", contentBoList);
            model.put("totalCount", contentBoList.size());
            model.put("type",request.getParameter("type"));

            log.setItemText(request.getParameter("type"));

            return new ModelAndView(model);

        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    @RequestMapping(url = "/addContent.do")
    @LogMethod(name="jump to add content page")
    public ModelAndView addContent(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String,Object> model = new HashMap<String,Object>();
            model.put("type",request.getParameter("type"));
            return new ModelAndView(model);

        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    @RequestMapping(url = "/addContentAction.do")
    @LogMethod(name="add a new content")
    public ModelAndView addContentAction(HttpServletRequest request, HttpServletResponse response) {
        try {

            String type = request.getParameter("type");
            String title = request.getParameter("title");
            String content = request.getParameter("content");
            String lgt = request.getParameter("lgt");
            String lat = request.getParameter("lat");
            String seq = request.getParameter("seq");
            String name = request.getParameter("coordName");
            String addr = request.getParameter("coordAddr");

            ContentBo bo = new ContentBo();
            bo.setType(type);
            bo.setContent(content);
            bo.setLatitude(lat);
            bo.setLongitude(lgt);
            bo.setTitle(title);
            bo.setCoordAddr(addr);
            bo.setCoordName(name);

            if(seq==null || seq.equals("") || !StringUtil.isInteger(seq)){
                bo.setSeq(99);
            }else{
                bo.setSeq(Integer.parseInt(seq));
            }

            contentService.addContent(bo);

            Map<String,Object> model = new HashMap<String,Object>();
            model.put("type",type);


            return new ModelAndView(new RedirectView("/admin/listContent.do"),model);

        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    @RequestMapping(url = "/viewContent.do")
    @LogMethod(name="view content list and content")
    public ModelAndView viewContent(HttpServletRequest request, HttpServletResponse response) {

        String id = request.getParameter("id");
        String type = request.getParameter("type");

        View view = null;
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("type",type);

        LogEntry log = this.getAdminSession(request).getCurrentLogEntry(request);
        StringBuilder logMsg = new StringBuilder();

        ContentBo contentBo = new ContentBo();
        if (id == null || id.equals("")) {
            logMsg.append("content type is ").append(type);
            List<ContentBo> contentBos = contentService.getContentByType(type);
            if (contentBos != null) {
                logMsg.append(" ;contents length is ").append(contentBos.size());
                if (type.equals("intro")) {
                    view = new JspView("/admin/viewContent.jsp");
                    model.put("data", contentBos.get(0));
                    model.put("isList", "false");

                } else {
                    view = new RedirectView("/admin/listContent.do");
                    model.put("data", contentBos);
                    model.put("isList", "true");
                }
            }
        } else {
            logMsg.append("content id is ").append(id);
            contentBo = contentService.getContentById(Integer.parseInt(id));
            view = new JspView("/admin/viewContent.jsp");
            model.put("data", contentBo);
            model.put("isList", "true");
        }
        log.setItemText(logMsg.toString());
        return new ModelAndView(view, model);
    }


    @RequestMapping(url = "/editContentAction.do")
    @LogMethod(name="edit a content")
    public ModelAndView editContentAction(HttpServletRequest request, HttpServletResponse response) {
        try {

            String type = request.getParameter("type");
            String content = request.getParameter("content");
            String lgt = request.getParameter("lgt");
            String lat = request.getParameter("lat");
            String id = request.getParameter("id");
            String entryDate = request.getParameter("entryDate");
            String seq = request.getParameter("seq");
            String name = request.getParameter("coordName");
            String addr = request.getParameter("coordAddr");

            ContentBo bo = new ContentBo();
            bo.setType(type);
            bo.setTitle(request.getParameter("title"));
            bo.setId(Integer.parseInt(id));
            bo.setContent(content);
            bo.setLatitude(lat);
            bo.setLongitude(lgt);
            bo.setEntryDate(DateUtil.strToDate(entryDate));
            bo.setCoordAddr(addr);
            bo.setCoordName(name);

            if(seq==null || seq.equals("") || !StringUtil.isInteger(seq)){
                bo.setSeq(99);
            }else{
                bo.setSeq(Integer.parseInt(seq));
            }
//            if (type.equals("view")) {
//                bo.setTitle("美景");
//            } else if (type.equals("food")) {
//                bo.setTitle("美食");
//            } else if (type.equals("tips")) {
//                bo.setTitle("小贴士");
//            } else if (type.equals("intro")) {
//                bo.setTitle("公司介绍");
//            }

            contentService.editContent(bo);

            Map<String,Object> model = new HashMap<String,Object>();
            model.put("id",id);
            model.put("type",type);

            if(!type.equals("intro")){

                return new ModelAndView(new RedirectView("/admin/listContent.do"),model);
            }   else{
                return new ModelAndView(new RedirectView("/admin/viewContent.do"),model);
            }

        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    @RequestMapping(url="/deleteContent.do")
    @LogMethod(name="delete content")
    public ModelAndView deleteContent(HttpServletRequest request,HttpServletResponse response){

        Map<String,Object> model = new HashMap<String,Object>();

        String id = request.getParameter("id");
        String type = request.getParameter("type");
        contentService.deleteContentById(Integer.parseInt(id));

        LogEntry log = this.getAdminSession(request).getCurrentLogEntry(request);
        log.setItemText("delete content, id is "+ id);

        model.put("type",type);
        View view = new RedirectView("/admin/listContent.do");
        return new ModelAndView(view,model);
    }


    ///////////////////////////////////////


    @RequestMapping(url = "/session/listSession.do")
    @LogMethod(name = "list session ")
    public ModelAndView sessionList(HttpServletRequest request, HttpServletResponse response) {

        try {
            String day = request.getParameter("day");
            String dayToPage = request.getParameter("day");
            if(day!=null && !day.equals("")){
                day = DateUtil.dateToStr(DateUtil.strToDate(day,"yyyy-MM-dd"),"MM-dd-yyyy");
                dayToPage = DateUtil.dateToStr(DateUtil.strToDate(day,"yyyy-MM-dd"),"yyyy-MM-dd");
            }
            String section = request.getParameter("section");
            List<ContentBo> contentBoList = contentService.getSessionByDayAndSection(day,section);
            Map<String, Object> model = new HashMap<String, Object>();
            model.put("results", contentBoList);
            model.put("totalCount", contentBoList.size());
            model.put("section",section);
            model.put("day",request.getParameter("day"));
            return new ModelAndView(model);

        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    @RequestMapping(url = "/session/addSession.do")
    @LogMethod(name="jump to add session page")
    public ModelAndView addSession(HttpServletRequest request, HttpServletResponse response) {

        Map<String,Object> model = new HashMap<String,Object>();

        return new ModelAndView(model);
    }

    @RequestMapping(url = "/session/addSessionAction.do",formCommand = "addSession")
    @LogMethod(name="add a new session")
    public ModelAndView addSessionAction(HttpServletRequest request, HttpServletResponse response,ContentForm form) {
        Map<String,Object> model = new HashMap<String,Object>();

        ContentBo bo = ObjectUtil.copyProperties(form,ContentBo.class);

        if(form.getSeq()==null){
            bo.setSeq(99);
        }else{
            bo.setSeq(form.getSeq());
        }

        MultiValueMap url = uploadFilesToFtp(request, "filePic", null);
        if (null != url.get("filePic")) {
            String fileName = url.get("filePic").toString();
            bo.setPicPath(fileName.substring(1, fileName.length() - 1));
        }
        contentService.addContent(bo);

        return new ModelAndView(new RedirectView("/admin/session/listSession.do"),model);
    }

    @RequestMapping(url = "/session/deleteSession.do")
    @LogMethod(name="delete session")
    public ModelAndView delSession(HttpServletRequest request, HttpServletResponse response) {
        Map<String,Object> model = new HashMap<String,Object>();

        String id = request.getParameter("id");
        contentService.deleteContentById(Integer.parseInt(id));
        return new ModelAndView(new RedirectView("/admin/session/listSession.do"),model);
    }

    @RequestMapping(url = "/session/viewSession.do")
    @LogMethod(name="jump to session detial page")
    public ModelAndView viewSession(HttpServletRequest request, HttpServletResponse response) {

        Map<String,Object> model = new HashMap<String,Object>();
        String id =request.getParameter("id");
        ContentBo bo = contentService.getContentById(Integer.parseInt(id));
        String link = "http://"+this.getConfig().getFtpHost()+this.getConfig().getFtpDownLoadPath()+"/";
        model.put("data",bo);
        model.put("link",link);

        return new ModelAndView(model);
    }

    @RequestMapping(url = "/session/editSession.do",formCommand = "viewSession")
    @LogMethod(name = "edit session")
    public ModelAndView editSession(HttpServletRequest request, HttpServletResponse response,ContentForm form) {

        Map<String,Object> model = new HashMap<String,Object>();

        ContentBo bo = ObjectUtil.copyProperties(form, ContentBo.class);

        String fileName = null;
        if(form.getPicPath()!=null && !form.getPicPath().equals("")){
            fileName = form.getPicPath().substring(form.getPicPath().lastIndexOf("/") + 1, form.getPicPath().lastIndexOf("."));
        }
        MultiValueMap url = uploadFilesToFtp(request, "filePic", fileName);
        if (null != url.get("filePic")) {
            String iconName = url.get("filePic").toString();
            bo.setPicPath(iconName.substring(1, iconName.length() - 1));
        } else{
            bo.setPicPath(fileName);
        }
        contentService.editContent(bo);

        return new ModelAndView(new RedirectView("/admin/session/listSession.do"),model);
    }





}
